import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flustars/flustars.dart';
import 'package:sprintf/sprintf.dart';
import 'errorhandle.dart';

/**
 * 拦截器
 */
class LoggingInterceptor extends Interceptor {
  DateTime? startTime;
  DateTime? endTime;

  @override
  onRequest(RequestOptions options, RequestInterceptorHandler handler,) {
  // onRequest(RequestOptions options,) {
    startTime = DateTime.now();
    print("----------Start----------");
    print("RequestUrl: " + options.baseUrl + options.path);
    print("RequestMethod: " + options.method);
    print("RequestHeaders:" + options.headers.toString());
    print("RequestContentType: ${options.contentType}");
    print("RequestData: ${options.data.toString()}");
    return super.onRequest(options,handler);
    // return super.onRequest(options);
  }

  @override
  onResponse(Response response, ResponseInterceptorHandler handler,) {
  // onResponse(Response response, ) {
    endTime = DateTime.now();
    int duration = endTime!.difference(startTime??DateTime.now()).inMilliseconds;
    LogUtil.e("----------End: $duration 毫秒----------");
    // return super.onResponse(response,);
    return super.onResponse(response,handler);
  }

  @override
  onError(DioError err, ErrorInterceptorHandler handler,) {
  // onError(DioError err,) {
    LogUtil.e("----------Error-----------");
    return super.onError(err,handler);
    // return super.onError(err,);
  }
}

class AdapterInterceptor extends Interceptor {
  static const String MSG = "userTip";
  static const String SLASH = "\"";
  static const String ERROR = "validateErrors";

  static const String DEFAULT = "\"无返回信息\"";
  static const String NOT_FOUND = "未找到查询信息";

  static const String FAILURE_FORMAT = "{\"code\":%d,\"userTip\":\"%s\"}";

//  static const String SUCCESS_FORMAT = "{\"status\":0,\"data\":%s,\"message\":\"\"}";

  @override
  onResponse(Response response, ResponseInterceptorHandler handler,) {
  // onResponse(Response response,) {
    Response r = adapterData(response);
    return super.onResponse(r,handler);
    // return super.onResponse(r);
  }

  @override
  onError(DioError err, ErrorInterceptorHandler handler) {
  // onError(DioError err, ) {
    if (err.response != null) {
      adapterData(err.response!);
    }
    return super.onError(err,handler);
    // return super.onError(err,);
  }

  Response adapterData(Response response) {
    String result;
    // LogUtil.e('adapterData-->response=${response.toString()}');
    String content = response.data.toString();
    /// 成功时，直接格式化返回
    if (response.statusCode == ExceptionHandle.success ||
        response.statusCode == ExceptionHandle.success_not_content) {
      if (content == null || content.isEmpty) {
        content = DEFAULT;
      }
      result = content;
      response.statusCode = ExceptionHandle.success;
    } else {
      if (response.statusCode == ExceptionHandle.not_found) {
        /// 错误数据格式化后，按照成功数据返回
        result = sprintf(FAILURE_FORMAT, [response.statusCode, NOT_FOUND]);
        response.statusCode = ExceptionHandle.success;
      } else {
        if (content == null || content.isEmpty) {
          // 一般为网络断开等异常
          result = content;
        } else {
          String msg;
          try {
            content = content.replaceAll("\\", "");
            if (SLASH == content.substring(0, 1)) {
              content = content.substring(1, content.length - 1);
            }
            Map<String, dynamic> map = json.decode(content);
            if (map.containsKey(ERROR) &&
                map[ERROR].toString() != null &&
                map[ERROR].toString() != "null") {
              List errorJson = json.decode(map[ERROR].toString());
              if (errorJson.length == 1) {
                msg = errorJson[0][MSG];
              } else {
                if (map.containsKey(MSG)) {
                  msg = map[MSG];
                } else if (map.containsKey(MSG)) {
                  msg = map[MSG];
                } else {
                  msg = "";
                }
              }
            } else {
              if (map.containsKey(MSG)) {
                msg = map[MSG];
              } else if (map.containsKey(MSG)) {
                msg = map[MSG];
              } else {
                msg = "";
              }
            }
            result = sprintf(FAILURE_FORMAT, [response.statusCode, msg]);
            // 401 token失效时，单独处理，其他一律为成功
            if (response.statusCode == ExceptionHandle.unauthorized) {
              response.statusCode = ExceptionHandle.unauthorized;
            } else {
              response.statusCode = ExceptionHandle.success;
            }
          } catch (e) {
            LogUtil.e("异常信息：$e");
            // 解析异常直接按照返回原数据处理（一般为返回500,503 HTML页面代码）
            result = content;
          }
        }
      }
    }
    LogUtil.e('adapterData 输入结果-->$result');
    response.data = result;
    return response;
  }
}
